import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wuziqi/paint.dart';
import 'package:wuziqi/win.dart';

class WuZiQi3 extends StatefulWidget {
  const WuZiQi3({super.key});

  @override
  State<WuZiQi3> createState() => _WuZiQi3State();
}

class _WuZiQi3State extends State<WuZiQi3> {
  List<Offset> piece = <Offset>[]; //所有棋子的集合
  List<Offset> blackPiece = <Offset>[]; //黑棋集合
  List<Offset> WhitePiece = <Offset>[]; //白棋集合
  List<Widget> qiju = []; // 存储的棋局
  List<List<Offset>> bcpiece = []; // 存储的棋局中某局的所有棋子
  List<List<Offset>> bcblackPiece = []; // 存储的棋局中某局的所有黑子
  List<List<Offset>> bcWhitePiece = []; // 存储的棋局中某局的所有白子
  int bcpieceL = 0; // 棋局索引

  double width = 14 * 26;
  int cell = 14;

  final _TextController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    double sWidth = MediaQuery.of(context).size.width;
    double sHeight = MediaQuery.of(context).size.height;

    // width = sWidth - 50;

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(color: Colors.pink[50]),
        child: Stack(
          children: [
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  RepaintBoundary(
                    child: CustomPaint(
                      size: Size(width, width),
                      painter: QiPan(xian: cell),
                    ),
                  ),
                ],
              ),
            ),
            // 悔棋
            Positioned(
              left: sWidth < sHeight ? 20 : 40,
              bottom: sWidth < sHeight ? 100 : 180,
              child: GestureDetector(
                onTap: () {
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (context) {
                        return AlertDialog(
                          title: Text("提示"),
                          content: Text("是否确认"),
                          actions: [
                            TextButton(
                                onPressed: () {
                                  if (piece.isNotEmpty) {
                                    piece.removeLast();
                                    if (piece.length % 2 == 0) {
                                      //最后一步为白棋
                                      WhitePiece.removeLast();
                                    } else {
                                      //最后一步为黑棋
                                      blackPiece.removeLast();
                                    }
                                    print(piece);
                                  }
                                  setState(() {});
                                  Navigator.of(context).pop();
                                },
                                child: Text("确定")),
                            TextButton(
                                onPressed: () {
                                  Navigator.of(context).pop();
                                  setState(() {});
                                },
                                child: Text("取消")),
                          ],
                        );
                      });
                },
                child: Container(
                  width: 120,
                  height: 50,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25),
                      color: Colors.blue),
                  child: Center(child: Text('悔棋')),
                ),
              ),
            ),
            // 保存快照
            Positioned(
              bottom: sWidth < sHeight ? 100 : 100,
              right: sWidth < sHeight ? 20 : sWidth - 160,
              child: GestureDetector(
                onTap: () {
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (context) {
                        return AlertDialog(
                          title: const Text("输入棋局名称"),
                          content: TextField(
                            controller: _TextController,
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(10),
                            ],
                            decoration: const InputDecoration(
                              hintText: '10个字符以内',
                            ),
                          ),
                          actions: [
                            TextButton(
                                onPressed: () {
                                  bcpiece.add([]);
                                  bcWhitePiece.add([]);
                                  bcblackPiece.add([]);
                                  bcpiece[bcpieceL].addAll(piece);
                                  // bcpiece = List.from(piece);
                                  bcWhitePiece[bcpieceL].addAll(WhitePiece);
                                  bcblackPiece[bcpieceL].addAll(blackPiece);
                                  bcpieceL++;
                                  qiju.add(qijuBox(
                                      bcpieceL - 1, _TextController.text));
                                  setState(() {});
                                  print(piece);
                                  Navigator.of(context).pop();
                                },
                                child: Text("确定")),
                            TextButton(
                                onPressed: () {
                                  Navigator.of(context).pop();
                                  setState(() {});
                                },
                                child: Text("取消")),
                          ],
                        );
                      });
                },
                child: Container(
                  width: 120,
                  height: 50,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25),
                      color: Colors.blue),
                  child: Center(child: Text('保存棋局')),
                ),
              ),
            ),
            // 存储棋局

            Positioned(
              top: sWidth < sHeight ? 30 : sHeight / 2 - 100,
              left: sWidth < sHeight ? sWidth / 2 - 100 : sWidth - 260,
              child: Container(
                alignment: Alignment.topCenter,
                width: 200,
                height: 200,
                decoration: BoxDecoration(color: Colors.blue[100]),
                child: ListView(padding: EdgeInsets.zero, children: [
                  Column(
                    children: qiju,
                  )
                ]),
              ),
            ),
            Positioned(
              top: 100,
              left: 40,
              child: Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                    border: Border.all(width: 1, color: Colors.black26)),
                child: Center(
                  child: Container(
                    width: 30,
                    height: 30,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(15),
                        color: piece.length % 2 == 0
                            ? Colors.black
                            : Colors.white),
                  ),
                ),
              ),
            ),
            //重新开始
            Positioned(
              bottom: sWidth < sHeight ? 100 : 20,
              left: sWidth < sHeight ? sWidth / 2 - 60 : 40,
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (context) {
                            return AlertDialog(
                              title: Text("提示"),
                              content: Text("是否确认"),
                              actions: [
                                TextButton(
                                    onPressed: () {
                                      piece.clear();
                                      WhitePiece.clear();
                                      blackPiece.clear();
                                      setState(() {});
                                      Navigator.of(context).pop();
                                    },
                                    child: Text("确定")),
                                TextButton(
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                      setState(() {});
                                    },
                                    child: Text("取消")),
                              ],
                            );
                          });
                    },
                    child: Container(
                      width: 120,
                      height: 50,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25),
                          color: Colors.blue),
                      child: Center(child: Text('重新开始')),
                    ),
                  ),
                ],
              ),
            ),

            // 下棋
            Center(
              child: Listener(
                child: CustomPaint(
                  size: Size(width, width), //指定画布大小
                  painter: QiZi(offset: piece, width: width, xian: cell),
                ),
                onPointerUp: (event) {
                  var qizi = QiZixy(event.localPosition);
                  if (piece.contains(qizi)) {
                    print('已有棋子');
                  } else {
                    piece.add(qizi);
                    QiZi(offset: piece, width: width, xian: cell);
                    // print(bcpiece);
                    // print(blackPiece);
                    print(piece);
                    print('黑棋${blackPiece}');
                  }
                  if (piece.length % 2 == 1) {
                    blackPiece.add(qizi);
                    if (Win(qizi, false, blackPiece, width, cell)) {
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (context) {
                            return AlertDialog(
                              title: Text("提示"),
                              content: Text("黑棋获胜"),
                              actions: [
                                TextButton(
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                      setState(() {});
                                    },
                                    child: Text("确定")),
                                TextButton(
                                    onPressed: () {
                                      piece.clear();
                                      blackPiece.clear();
                                      WhitePiece.clear();
                                      Navigator.of(context).pop();
                                      setState(() {});
                                    },
                                    child: Text("重新开始")),
                              ],
                            );
                          });
                    }
                  } else {
                    WhitePiece.add(qizi);
                    if (Win(qizi, true, WhitePiece, width, cell)) {
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (context) {
                            return AlertDialog(
                              title: Text("提示"),
                              content: Text("白棋获胜"),
                              actions: [
                                TextButton(
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                      setState(() {});
                                    },
                                    child: Text("确定")),
                                TextButton(
                                    onPressed: () {
                                      piece.clear();
                                      blackPiece.clear();
                                      WhitePiece.clear();
                                      Navigator.of(context).pop();
                                      setState(() {});
                                    },
                                    child: Text("重新开始")),
                              ],
                            );
                          });
                    }
                  }
                  setState(() {});
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Container qijuBox(int l, String text) {
    return Container(
      color: Colors.pink[100],
      padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // Text('棋局${l + 1}'),
          Text(text),
          Row(
            children: [
              GestureDetector(
                  onTap: () {
                    piece = List.from(bcpiece[l]);
                    WhitePiece = List.from(bcWhitePiece[l]);
                    blackPiece = List.from(bcblackPiece[l]);
                    setState(() {});
                    print(piece);
                    print(bcpiece);
                  },
                  child: Container(
                      // padding: EdgeInsets.all(5),
                      // color: Colors.yellow,
                      child: Text('应用'))),
              SizedBox(
                width: 10,
              ),
              GestureDetector(
                  onTap: () {
                    qiju[l] = Container();
                    setState(() {});
                  },
                  child: Text('删除')),
            ],
          )
        ],
      ),
    );
  }

  Offset QiZixy(Offset offset) {
    double ddx = 0; //最终棋子的x坐标
    double ddy = 0; //最终棋子的y坐标
    double level = width / cell;
    int modx = offset.dx ~/ level;
    int mody = offset.dy ~/ level;
    if (offset.dx - level * modx <= level / 2) {
      ddx = level * modx;
    } else {
      ddx = level * (modx + 1);
    }

    if (offset.dy - level * mody <= level / 2) {
      ddy = level * mody;
    } else {
      ddy = level * (mody + 1);
    }
    return Offset(ddx, ddy);
  }
}
